package com.biodiv.miracle.web.servlet;

import com.biodiv.miracle.web.interceptor.InterceptorRegistration;
import com.biodiv.miracle.web.interceptor.RequestMappingCache;
import com.biodiv.miracle.web.interceptor.HandlerInterceptor;
import com.biodiv.miracle.web.handler.HandlerMethod;
import com.biodiv.miracle.web.handler.MappingObject;
import com.biodiv.miracle.web.interceptor.InterceptorRegistry;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: tianquan
 * @CreateTime: 2025-05-25  21:04
 * @Description: TODO
 */
public class HttpServletBean extends HttpServlet {

    // 拦截器注册
    private final InterceptorRegistry interceptorRegistry = new InterceptorRegistry();

    // 请求映射缓存
    private final RequestMappingCache requestMappingCache = new RequestMappingCache();

    protected MappingObject addRequestMapping(String requestMethod, String url) {
        return requestMappingCache.addRequestMapping(requestMethod, url);
    }

    protected void addHandlerMethod(MappingObject mappingObject, HandlerMethod handlerMethod) {
        requestMappingCache.addHandlerMethod(mappingObject, handlerMethod);
    }

    public HandlerMethod getHandlerMethod(String requestMethod, String url) {
        return requestMappingCache.getHandlerMethod(requestMethod,url);
    }

    protected List<MappingObject> getRequestMapping() {
        return requestMappingCache.getRequestMapping();
    }

    protected InterceptorRegistry getInterceptorRegistry() {
        return interceptorRegistry;
    }

    public List<HandlerInterceptor> getInterceptors(HttpServletRequest request) {
        String url = request.getRequestURI();
        List<HandlerInterceptor> interceptors = new ArrayList<>();
        // 获取所有拦截器
        List<InterceptorRegistration> interceptorRegistrations = interceptorRegistry.getInterceptors();
        for (InterceptorRegistration interceptor : interceptorRegistrations) {
            HandlerInterceptor handlerInterceptor = interceptor.match(url);
            if (handlerInterceptor != null) {
                interceptors.add(handlerInterceptor);
            }
        }
        return interceptors;
    }

}
